#!/usr/bin/perl -w

BEGIN {
	push @INC,"/usr/local/cluster/lib/perl";
}

use Sys::Hostname;
use Data::Dumper;
use English;
use XML::Simple;
use Getopt::Long;
use File::Basename;
use cld_client;
use clutils;
use cldlockc;
use lvm;
use clnet qw(CLNET_assign_ips2 CLNET_unassign_ips2 CLNET_check_ping2);

$_PRG=basename($0);
$ARG_verbose=0;
$ARG_application=undef;
$ARG_add=0;
$ARG_remove=0;

sub usage {
	print STDERR "
Usage: $_PRG --application X [--add|--remove] --verbose

The $_PRG tool will allow you to manually assign the IP addresses
associated with the particular application to the current host.

It will ICMP ping all IP addresses first and if any are found to currently
exist it will abort with an error (since the clash might cause untold 
network issues).

Written by Simon Edwards, www.linuxha.net, (C) 2003-2013.
";
	exit(1);
}

Getopt::Long::Configure("no_ignore_case");
if(!GetOptions(
	"application|A=s"	=> \$ARG_application,
	"remove"		=> \$ARG_remove,
	"add"			=> \$ARG_add,
	"verbose|V"		=> \$ARG_verbose,
	)) {
	usage();
}

$ARG_add=1 if $ARG_add+$ARG_remove==0;
usage() if $ARG_add+$ARG_remove==2;
usage() if !defined($ARG_application);

$ARG_config="/etc/cluster/clconf.xml";
if(! -f "/etc/cluster/$ARG_application/appconf.xml") {
	exit(1);
}

($xml,$err,@errmsg)=validate_cluster_cfg($ARG_config,1);
if(!defined($xml)) {
	errmsg($_) foreach(@errmsg);
	exit(1);
}
logmsg("Validated cluster configuration.");
($xml2,$err,@errmsg)=validate_application_cfg($ARG_application,1);
if(!defined($xml2)) {
	errmsg($_) foreach(@errmsg);
	exit(1);
}
logmsg("Validated application configuration.");

if($ARG_add) {
	($res,@errs)=CLNET_check_ping2(xml=>$xml,appxml=>$xml2);
	if($res!=1) {
		errmsg("Errors found whilst checking for existing IP addresses:");
		errmsg($_) foreach(@errs);
		exit(1);
	}
	logmsg("Validated no application IP addresses are in use.");
	($res,@errs)=CLNET_assign_ips2(xml=>$xml,appxml=>$xml2);
	if(!$res) {
		errmsg("Failed to allocate IP addresses:");
		errmsg($_) foreach(@errs);
		exit(1);
	} else {
		logmsg("Allocated IP addresses.");
	}
} else {
	($res,@errs)=CLNET_unassign_ips2(xml=>$xml,appxml=>$xml2);
	if(!$res) {
		errmsg("Failed to deallocate IP addresses:");
		errmsg($_) foreach(@errs);
		exit(1);
	} else {
		logmsg("Deallocated IP addresses.");
	}
}
exit(0);
